<?php
namespace app\index\controller;
use think\Controller;
use think\Db; 
use think\Request;
use other\Aes;
use think\Cache;
use other\polyvSDK;
use app\index\model\KnowUserRecord;
use app\index\model\KnowUser;
use app\index\model\KnowUserTraining;
use app\index\model\KnowUserNav;



class Test  extends \app\index_new\controller\Common
{

    public function polyv(){
        $user = $this->user;
        $username = $user['phone'].'  正在观看';
        $secretkey = "YbcnWH2IXl";
        $vid=$_GET['vid'];
        $t = $_GET["t"];
        $code = $_GET["code"];
        $fontSize="14";
        $fontColor="FFF";
        $speed="200";
        $filter="on";
        $setting="3";
        $alpha="0.3";
        $filterAlpha="1";
        $filterColor="dddddd";
        $blurX="2";
        $blurY="2";
        $tweenTime="1";
        $interval="5";
        $lifeTime="3";
        $strength="4";
        $show="on";
        $msg="Errormessage!";
        if($_GET["callback"]){
            $status = 1;
        }else {
            $status = 2;
        }
        $callback = '';
        if(!empty($_GET["callback"])) $callback = $_GET["callback"];
        if($callback!=''){
            $sign=md5("vid=$vid&secretkey=$secretkey&username=$username&code=$code&status=$status&t=$t");
            $array = Array("status"=>$status,"username"=>$username,"sign"=>$sign,"msg"=>$msg,"fontSize"=>$fontSize,"fontColor"=>$fontColor,"speed"=>$speed,"filter"=>$filter,"setting"=>$setting,"alpha"=>$alpha,"filterAlpha"=>$filterAlpha,"filterColor"=>$filterColor,"blurX"=>$blurX,"blurY"=>$blurY,"tweenTime"=>$tweenTime,"interval"=>$interval,"lifeTime"=>$lifeTime,"strength"=>$strength,"show"=>$show,);
            $Json = json_encode($array);
            echo $callback."(".$Json.")";
        } else{
            $sign = md5("vid=$vid&secretkey=$secretkey&username=$username&code=$code&status=$status&t=$t&msg=$msg&fontSize=$fontSize&fontColor=$fontColor&speed=$speed&filter=$filter&setting=$setting&alpha=$alpha&filterAlpha=$filterAlpha&filterColor=$filterColor&blurX=$blurX&blurY=$blurY&interval=$interval&lifeTime=$lifeTime&tweenTime=$tweenTime&strength=$strength&show=$show");

            $array = Array("status"=>$status,"username"=>$username,"sign"=>$sign,"msg"=>$msg,"fontSize"=>$fontSize,"fontColor"=>$fontColor,"speed"=>$speed,"filter"=>$filter,"setting"=>$setting,"alpha"=>$alpha,"filterAlpha"=>$filterAlpha,"filterColor"=>$filterColor,"blurX"=>$blurX,"blurY"=>$blurY,"tweenTime"=>$tweenTime,"interval"=>$interval,"lifeTime"=>$lifeTime,"strength"=>$strength,"show"=>$show,);
            $Json = json_encode($array);
            echo $Json;
        }
    }

	public function index(){
        $data = Db::table('college')->field('collegeName as title,collegeId as id')->select();
        echo json_encode($data);
    }

    public function lists(){
        $request = Request::instance();
        $id = $request->param('id');
        $data = Db::table('department')->field('depName as title,depId as id')->where('college_collegeId',$id)->select();
        echo json_encode($data);
    }

    public function suxuetang(){
        $connect = array(
                    'type'    => 'mysql',
                    'hostname'    => 'rm-2ze0dh9zv8292pl76.mysql.rds.aliyuncs.com',
                    'database'    => 'suxuetang',
                    'username'    => 'itbaizhan_root',
                    'password'    => 'Data2020Sxt186@#$',
                );
        $count = Db::connect($connect)->table('know_user')
            ->where(['register_time'=>['like',date('Y-m').'%']])->count();
        return $count;
    }

    public function bjsxt(){
        $connect = array(
                    'type'    => 'mysql',
                    'hostname'    => 'rm-2ze0dh9zv8292pl76.mysql.rds.aliyuncs.com',
                    'database'    => 'bjsxt',
                    'username'    => 'itbaizhan_root',
                    'password'    => 'Data2020Sxt186@#$',
                );
        $count = Db::connect($connect)->table('wp_users')
            ->where(['user_registered'=>['like',date('Y-m').'%']])->count();
        return $count;
    }



    /*public function zhuanma(){
        $page = isset($_GET['page']) ? $_GET['page'] : 1;
        $data_count = Db::table('course')
            ->field('fileid')
            ->where(['video_url'=>['like','%avi'],'nav_id'=>['in','9,10']])
            ->select();
        $count = count($data_count);
        $length = 50;
        $offset = ($page-1)*$length;
        $data = Db::table('course')->field('fileid')->where(['video_url'=>['like','%avi'],'nav_id'=>['in','9,10']])->order('course_id')->limit($offset,$length)->select();
        foreach ($data as $key => $v) {
            $url = $this->test($v['fileid']);
            Db::table('course')->where('fileid',$v['fileid'])->update(['video_url'=>$url]);
        }
    }

    public function test($fileid){
        $secretKey = 'IshR2dKvGf3KSWRDvhP5hl3CC7tV3TDl';//换成你的secretKey
        $secretId = 'AKIDjcL2bKzT30fFl8tVAlJkCSabTVOGGbwD';//换成你的secretId
        $action = 'GetVideoInfo';//换成你需要的接口名
        $queryString = 'fileId='.$fileid.'&infoFilter.1=transcodeInfo';//换成接口参数列表
        $method = 'GET';//GET或POST

        $rand = rand(100,10000000);
        $time = time();

        $url = 'vod.api.qcloud.com/v2/index.php?Action=' . $action . '&Nonce=' . $rand . '&Region=gz&SecretId=' . $secretId . '&SignatureMethod=HmacSHA256&Timestamp=' . $time . '&' . $queryString;
        $srcStr = $method . $url;
        $signStr = base64_encode(hash_hmac('sha256', $srcStr, $secretKey, true));
        $url .= "&Signature=" . urlencode($signStr);
        $detail_url = "https://" . $url . "\n";
        $content = json_decode(file_get_contents($detail_url),true);
        foreach ($content['transcodeInfo']['transcodeList'] as $key => $v) {
           if($v['templateName'] == 'MP4-全高清-FHD'){
                $detail = $v['url'];
           }
        }
        return $detail;
    }*/

    public function changetime(){
        $length = 500;
        $page = isset($_GET['page']) ? $_GET['page'] : 1;
        $offset = ($page-1)*$length;
        $course_data = Db::table('course')->field('vid,course_id')->where("vid != '' and video_time is null")->limit($offset,$length)->select();
        // echo Db::table('course')->getLastSql();die;
        // print_r($course_data);die;
        foreach ($course_data as $key => $v) {
            echo $v['vid'].'<br>';
            if($v['vid']){
                $detail = video_detail($v['vid']);
                if($detail){
                    $time = $detail['data'][0]['duration'];
                    $time1 = substr($time,0, 2);
                    $time2 = substr($time, 3,2);
                    $time3 = substr($time, 6);
                    $video_time = $time1*60*60+$time2*60+$time3;
                    Db::table('course')->where('course_id',$v['course_id'])->update(['video_time'=>$video_time]);
                }else{
                    continue;
                }
            }
                
        }
    }


    public function changetime1(){
        $length = 500;
        $page = isset($_GET['page']) ? $_GET['page'] : 1;
        $offset = ($page-1)*$length;
        $course_data = Db::table('course')->field('vid,course_id')->where("vid='64901470c487be5fcbc17ef5f87563bd_6'")->limit($offset,$length)->select();
        // echo Db::table('course')->getLastSql();die;
        // print_r($course_data);die;
        foreach ($course_data as $key => $v) {
            echo $v['vid'].'<br>';
            if($v['vid']){
                $detail = video_detail($v['vid']);
                if($detail){
                    $time = $detail['data'][0]['duration'];
                    $time1 = substr($time,0, 2);
                    $time2 = substr($time, 3,2);
                    $time3 = substr($time, 6);
                    $video_time = $time1*60*60+$time2*60+$time3;
                    Db::table('course')->where('course_id',$v['course_id'])->update(['video_time'=>$video_time]);
                }else{
                    continue;
                }
            }
                
        }
    }


    public function changehits(){
        $length = 500;
        $page = isset($_GET['page']) ? $_GET['page'] : 1;
        $offset = ($page-1)*$length;
        $course_data = Db::table('course')->field('course_id,hits')->where("hits<1000")->limit($offset,$length)->select();
        // echo Db::table('course')->getLastSql();die;
        // print_r($course_data);die;
        foreach ($course_data as $key => $v) {
            $hits = rand(5000, 10000);
            Db::table('course')->where('course_id',$v['course_id'])->update(['hits'=>$hits]);
        }
    }



    public function getSss(){
        $length = 500;
        $page = isset($_GET['page']) ? $_GET['page'] : 1;
        $data = Db::table('know_user_log')->where('time',['<=','2019-07-25 10:05:25'],['>=','2019-07-24 17:25:00'])->page($page,$length)->order('time desc')->select();
        foreach ($data as $key => $v) {
            $arr = Db::table('know_user_record')->where(['id'=>$v['course_id'],'type'=>3,'user_id'=>$v['user_id']])->find();
            if(!$arr){
                $course = Db::table('course')->where(['course_id'=>$v['course_id']])->find();
                KnowUserRecord::addRecord($v['user_id'],$course,$v['course_id']);
            }
        }
    }

    /**
     * 未登录提醒
     */
    public function nologinmessage($page = 1){
        $request = Request::instance();
        $total = $request->param('total');
        $pages = $request->param('pages');
        $threeTime = date('Y-m-d',time()-86400*3);
        $pagesize = 500;
        if(!$total){
            $total = Db::table('know_user')->whereTime('login_time', '<=', $threeTime)->count();
            $pages = ceil($total/$pagesize);
        }
        $data = Db::table('know_user')->field('know_user_id as user_id,know_nickname as nickname')->whereTime('login_time', '<=', $threeTime)->page($page,$pagesize)->select();
        foreach ($data as $key => $v) {
            Db::table('message')->insert(['userId'=>$v['user_id'],'time'=>time(),'content'=>'【百战程序员】亲爱的'.$v['nickname'].'学员，是我不够吸引吗？好久都没来找我了，点一点，惊喜不断！点击http://t.cn/AiDmRz8H']);
        }
        if($pages > $page) {
            $offset = $pagesize*($page-1);
            $page++;
            $creatednum = $offset + count($data);
            $percent = round($creatednum/$total, 2)*100;
            $message = '总共 '.$total.' 个未登录用户 - 已完成 '.$creatednum.' 条（'.$percent.'%）';
            $this->success($message,url('nologinmessage',['page'=>$page,'pages'=>$pages,'total'=>$total]),'',1);
        } else {
            $message = '更新成功';
            $this->success($message,'end','',1);
        }
    }


    public function nologinvip($page = 1){
        $request = Request::instance();
        $total = $request->param('total');
        $pages = $request->param('pages');
        $threeTime = date('Y-m-d H:i:s',time()-86400*3);
        $pagesize = 500;
        if(!$total){
            $totalData = Db::table('know_user')->field('user_id')->join('know_user_nav','user_id=know_user_id')->whereTime('login_time', '<=', $threeTime)->group('user_id')->select();
            $total = count($totalData);
            $pages = ceil($total/$pagesize);
        }
        $data = Db::table('know_user')->field('know_user_id as user_id,know_nickname as nickname')->join('know_user_nav','user_id=know_user_id')->whereTime('login_time', '<=', $threeTime)->group('user_id')->page($page,$pagesize)->select();
        foreach ($data as $key => $v) {
            Db::table('message')->insert(['userId'=>$v['user_id'],'time'=>time(),'content'=>'【百战程序员】亲爱的'.$v['nickname'].'学员，是我不够吸引吗？好久都没来找我了，点一点，惊喜不断！点击http://t.cn/AiDmRz8H']);
        }
        if($pages > $page) {
            $offset = $pagesize*($page-1);
            $page++;
            $creatednum = $offset + count($data);
            $percent = round($creatednum/$total, 2)*100;
            $message = '总共 '.$total.' 个未登录用户 - 已完成 '.$creatednum.' 条（'.$percent.'%）';
            $this->success($message,url('nologinvip',['page'=>$page,'pages'=>$pages,'total'=>$total]),'',1);
        } else {
            $message = '更新成功';
            $this->success($message,'end','',1);
        }
    }


    public function studynumvip($page = 1){
        // 00 10 * * 01 cd /home/wwwroot/online && /usr/bin/php think Task >> runtime/message/2019.log 2>&1
        $request = Request::instance();
        $total = $request->param('total');
        $pages = $request->param('pages');
        $pagesize = 100;
        if(!$total){
            $totalData = Db::table('know_user')->field('user_id')->join('know_user_nav','user_id=know_user_id')->group('user_id')->select();
            $total = count($totalData);
            $pages = ceil($total/$pagesize);
        }
        $data = Db::table('know_user')->field('know_user_id as user_id,know_nickname as nickname')->join('know_user_nav','user_id=know_user_id')->group('user_id')->page($page,$pagesize)->select();
        foreach ($data as $key => $v) { 
            $StudyCount = KnowUser::getrecord($v['user_id']);
            $TrainCount = KnowUser::gettraining($v['user_id']);
            Db::table('message')->insert(['userId'=>$v['user_id'],'time'=>time(),'content'=>'【百战程序员】亲爱的'.$v['nickname'].'学员，已经努力学习'.$StudyCount.'课节，实操作业已完成'.$TrainCount.'，真棒！课程已更新，详细记录请点击http://t.cn/AiDmRz8H','type'=>'用户记录统计']);
        }
        if($pages > $page) {
            $offset = $pagesize*($page-1);
            $page ++;
            $creatednum = $offset + count($data);
            $percent = round($creatednum/$total, 2)*100;
            $message = '总共 '.$total.' 个未登录用户 - 已完成 '.$creatednum.' 条（'.$percent.'%）';
            $this->success($message,url('studynumvip',['page'=>$page,'pages'=>$pages,'total'=>$total]),'',1);
        } else {
            $message = '更新成功';
            $this->success($message,'end','',1);
        }
    }


    public function changeLogin(){
        $message = file_get_contents('https://www.bz6000.cn/user/pythons');
        // print_r($message);die;
        $newsList = preg_match('%<div.*?class="paycourse_ser".*?>(.*?)</table>%si', $message, $newsA);
        $newsUl = preg_match_all('%<tr>(.*?)</tr>%si', $newsA[1], $newsDetail);
        $weekSort = count($newsDetail[1])*2;
        foreach ($newsDetail[1] as $key => $v) {
            preg_match('%<td class="td4">(.*?)</td>%si', $v, $week);
            $title = explode('<br/>', $week[1]);
            Db::table('nav_week')->insert(['title'=>$title[1],'nav_id'=>17,'sort'=>$weekSort]);
            $weekId = Db::table('nav_week')->getLastInsID();
            $weekSort = $weekSort-2;
            preg_match('%<td class="td5">.*?<p>(.*?)</p>.*?</td>%si', $v, $days);
            $dayData = explode('<br/>', $days[1]);
            $dayData = array_filter($dayData);
            $daySort = count($dayData)*2;
            foreach ($dayData as $kd => $vd) {
                Db::table('nav_week_days')->insert(['title'=>trim($vd),'nav_id'=>17,'week_id'=>$weekId,'sort'=>$daySort]);
                $daySort = $daySort-2;
            }
        }
        echo "done.";       //输出操作完成标记
    }


    /*private $wx_appid = 'wx2d117f30f174bc43';
    private $wx_appsecret = '4f410e432c0f06c12f54e926b149db42';
    public function wechat(){
       $this->redirect('https://open.weixin.qq.com/connect/qrconnect?appid='. $this->wx_appid .'&redirect_uri=https://www.itbaizhan.com/index/test/huidiao.html&response_type=code&scope=snsapi_login&state=' . md5 ( uniqid ( rand (), true ) ) . '#wechat_redirect');
    }

    public function huidiao(){
        session_start();
        $info = $_GET;
        $code = $_GET['code'];
        $state = $_GET['state'];
        $rand = $_SESSION["wx_rand"];
        if ($code=='' && $rand!==$state) {
            exit();
        }else{
            $appid = 'wx2d117f30f174bc43'; 
            $appsecret = '4f410e432c0f06c12f54e926b149db42';
            $token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$appsecret.'&code='.$code.'&grant_type=authorization_code';
            $token = json_decode(file_get_contents($token_url),true);
            $r_token = $token['refresh_token'];
            $refresh_token_url = 'https://api.weixin.qq.com/sns/oauth2/refresh_token?appid='.$appid.'&grant_type=refresh_token&refresh_token='.$r_token;
            $refresh_token = json_decode(file_get_contents($refresh_token_url),true);
            $access_token=$refresh_token['access_token'];
            $openid=$refresh_token['openid'];

            $verify_access_token_url='https://api.weixin.qq.com/sns/auth?access_token='.$access_token.'&openid='.$openid;
            $res = json_decode(file_get_contents($verify_access_token_url),true);
            if ($res['errcode']==0 && $res['errmsg']== ok) {
                $user_info_url='https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token.'&openid='.$openid.'&lang=zh_CN';
                $user_info = json_decode(file_get_contents( $user_info_url),true);
                echo $user_info['unionid'];
            }
        }
    }*/


    public function assssing(){
        /*$typeIds = Db::table('class_nav_type')->where(['class_id'=>12])->value('type_id');
        $typeIds = explode(',', $typeIds);*/
        // print_r($typeIds);die;
        $sIds = ['1623'];
        $where = ['nav.is_show'=>1,'s_show'=>'yes','course.nav_id'=>17,'type.is_show'=>1];
        $where['course.s_id'] = ['in',$sIds];
        $time = Db::table('course')->where($where)
            ->join('nav','nav.nav_id=course.nav_id')
            ->join('type','type.type_id=course.type_id')
            ->join('specific','specific.s_id=course.s_id')
            ->sum('video_time');
        echo round($time/60/60,2);
    }
}
